package com.school.controller;

import com.school.common.Result;
import com.school.entity.User;
import com.school.service.UserService;
import com.school.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");
        
        User user = userService.login(username, password);
        
        // 生成token
        String token = TokenUtils.generateToken(user.getId(), user.getUsername());
        
        Map<String, Object> data = new HashMap<>();
        data.put("id", user.getId());
        data.put("username", user.getUsername());
        data.put("realName", user.getRealName());
        data.put("phone", user.getPhone());
        data.put("token", token);  // 添加token到返回数据
        
        log.info("用户登录成功: username={}, token={}", username, token);
        
        return Result.success("登录成功", data);
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Long> register(@Validated @RequestBody User user) {
        Long id = userService.register(user);
        return Result.success("注册成功", id);
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        return Result.success("退出成功");
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestParam String username) {
        User user = userService.findByUsername(username);
        // 清空密码字段，不返回给前端
        if (user != null) {
            user.setPassword(null);
        }
        return Result.success(user);
    }
}

